class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        set<ListNode*> s;
        ListNode* cur = head;
        while (cur) {
            if (s.count(cur))
                return cur;
            else {
                s.insert(cur);
            }
            cur = cur->next;
        }
        return nullptr;
    }
};